﻿#include <Windows.h>
#include <stdio.h>
#include <tchar.h>

/// @brief 封装创建进程的函数
/// @param lpApplicationName 程序名 
/// @param numCmds 命令行数量（不包含程序名）
/// @param cmds 命令行字符串数组
/// @param numEnvs 环境变量数量
/// @param envNames 环境变量名字符串数组
/// @param envValues 环境变量值字符串数组
/// @return 成功返回TRUE，失败返回FALSE
BOOL CreateProcessWithCmdAndEnviroment(LPCWSTR lpApplicationName,
	DWORD numCmds, WCHAR* cmds[],
	DWORD numEnvs, WCHAR* envNames[], WCHAR* envValues[]) {
	// 计算总的命令行字符串长度
	int num = 0;
	num += (wcslen(lpApplicationName) + 3);
	for (size_t i = 0; i < numCmds; i++)
		num += (wcslen(cmds[i]) + 1);
	num++;

	// 组装命令行字符串
	WCHAR* cmd = new WCHAR[num];
	wcscpy_s(cmd, num, L"\"");	// 用引号包裹程序路径，应对路径中包含空格的情况
	wcscat_s(cmd, num, lpApplicationName);
	wcscat_s(cmd, num, L"\"");
	for (size_t i = 0; i < numCmds; i++) {
		wcscat_s(cmd, num, L" ");
		wcscat_s(cmd, num, cmds[i]);
	}

	for (size_t i = 0; i < numEnvs; i++)
		SetEnvironmentVariable(envNames[i], envValues[i]);

	STARTUPINFO startupInfo = { sizeof(startupInfo) };
	PROCESS_INFORMATION processInfo;
	BOOL flag = CreateProcess(nullptr, cmd, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &startupInfo, &processInfo);
	delete[] cmd;

	return flag;
}

int _tmain() {
	// 设置命令行参数
	WCHAR cmd1[] = L"lixia";
	WCHAR cmd2[] = L"lishiyin";
	WCHAR* cmds[] = { cmd1,cmd2 };

	// 设置环境变量参数
	WCHAR envName1[] = L"env1";
	WCHAR envName2[] = L"env2";
	WCHAR envValue1[] = L"envValue1";
	WCHAR envValue2[] = L"envValue2";
	WCHAR* envNames[] = { envName1,envName2 };
	WCHAR* envValues[] = { envValue1,envValue2 };

	CreateProcessWithCmdAndEnviroment(L"E:\\Desktop\\WindowsViaC\\Debug\\LHTest.exe", 2, cmds, 2, envNames, envValues);
	return 0;
}

